package com.cz.ssyx.payment.controller;

import com.cz.ssyx.common.exception.MyException;
import com.cz.ssyx.common.result.Result;
import com.cz.ssyx.common.result.ResultCodeEnum;
import com.cz.ssyx.payment.service.PaymentInfoService;
import com.cz.ssyx.payment.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Objects;

/**
 * @descriptions:
 * @author: Joker.
 * @date: 2024/5/8 19:50
 * @version: 1.0
 */
@RestController
@RequestMapping("/api/payment/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    //调用微信支付系统生成预支付订单
    @GetMapping("/createJsapi/{orderNo}")
    public Result createJsapi(@PathVariable("orderNo") String orderNo) {
        Map<String, String> map = weixinService.createJsapi(orderNo);
        return Result.ok(map);
    }

    //查询订单支付状态
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable String orderNo) {
        //1.调用微信支付接口，查询支付状态
        Map<String,String> resultMap = weixinService.queryPayStatus(orderNo);

        //2.返回为null，则支付失败
        if (resultMap == null) {
            return Result.build(null, ResultCodeEnum.PAYMENT_FAIL);
        }

        //3.根据微信支付系统的返回值判定出支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {
            String out_trade_no = resultMap.get("out_trade_no");
            paymentInfoService.paySuccess(out_trade_no, resultMap);
        }


        //4.支付中
        return Result.build(null, ResultCodeEnum.PAYMENT_WAITING);
    }

}
